package com.authine.cloudpivot.ext.controller;

import com.authine.cloudpivot.engine.api.model.organization.DepartmentModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: brookpeng
 * @Date: 2022/3/9 19:48
 */
@Slf4j
@RestController
@RequestMapping("/public/pagesUse")
public class PagesUsePublicController extends BaseController {

    private  String adminId = "2c9280a26706a73a016706a93ccf002b";

    @PersistenceContext
    EntityManager entityManager;

    @GetMapping("changeCourseReviewFlowType")
    @Transactional
    public ResponseResult changeCourseReviewFlowType(@RequestParam String formId) {

        // 基层领导审批表单
        String approvalTableName = getBizObjectFacade().getTableName("DepartmentLeaderApproval");
        StringBuilder approvalSql = new StringBuilder();
        approvalSql.append("SELECT * FROM `" + approvalTableName + "` T WHERE T.id = '" + formId + "';");
        List<Map<String, Object>> approvalResultList = entityManager.createNativeQuery(approvalSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        String result = MapUtils.getString(approvalResultList.get(0), "Dropdown_spjg");

        // 评审意见表
        StringBuilder commentInfoSql = new StringBuilder();
        commentInfoSql.append("SELECT * FROM `h_biz_comment` T WHERE T.bizObjectId = '" + formId + "';");
        List<Map<String, Object>> commentInfoResultList = entityManager.createNativeQuery(commentInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        if (CollectionUtils.isEmpty(commentInfoResultList)) {
            return getErrResponseResult(500L, "未查询到审批意见数据");
        }
        // 审批意见
        String content = MapUtils.getString(commentInfoResultList.get(0), "content", "");

        // 基层领导审批表单_子表SheetInfo
        String sheetInfoTableName = getBizObjectFacade().getTableName("Sheet_kcsqlb");
        StringBuilder sheetInfoSql = new StringBuilder();
        sheetInfoSql.append("SELECT * FROM `" + sheetInfoTableName + "` T WHERE T.parentId = '" + formId + "';");
        List<Map<String, Object>> sheetInfoResultList = entityManager.createNativeQuery(sheetInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        String kcsbNewTableName = getBizObjectFacade().getTableName("kcsbNew");
        for (Map<String, Object> stringObjectMap : sheetInfoResultList) {
            String courseDataId = MapUtils.getString(stringObjectMap, "ShortTextCourseID");
            StringBuilder updateDQYWsql = new StringBuilder();
            updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ldspyj = '" + content + "', T.ldspzt = '" + result + "' WHERE T.id = '" + courseDataId + "'");
            int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
            log.info("\n=======更新业务状态回写成功,updateNum={}", updateNum);
        }
        return getOkResponseResult("success");
    }

    /**
     * 根据活动级别获取活动业务路线
     * @param hdjb
     * @return
     */
    @GetMapping("/businessLine")
    @Transactional
    public ResponseResult<String> businessLine(@RequestParam(required = false) String hdjb, @RequestParam(required = false) String dqyw, @RequestParam String kcsbId, @RequestParam(required = false) String fallBack) {

        log.info("\n=======▼▼▼▼▼▼根据活动级别获取活动业务路线Start▼▼▼▼▼▼,instanceId={}",kcsbId);
        // 业务路线
        String ywlx = "Undefined";

//        String userId = getUserId();
        UserModel user = getOrganizationFacade().getUser(adminId);

        // 部门领导评审子表表名
        String tableNameSheetInfo = getBizObjectFacade().getTableName("SheetInfo");
        StringBuilder subTableSelectSql = new StringBuilder();
        subTableSelectSql.append("SELECT * FROM `" + tableNameSheetInfo + "` T WHERE T.parentId = '" + kcsbId + "';");
        List<Map<String, Object>> courseInfoList = entityManager.createNativeQuery(subTableSelectSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
        StringBuilder ids = new StringBuilder();
        boolean flug = false;
        for (Map<String, Object> stringObjectMap : courseInfoList) {
            if (flug) {
                ids.append(";");
            }
            ids.append(stringObjectMap.get("ShortTextCourseID"));
            flug = true;
        }

        // 如果参数传入活动级别，则依据活动级别获取业务路线
        if (StringUtils.isNotEmpty(hdjb)) {
            String ywxlTableName = getBizObjectFacade().getTableName("ywxlNew");
            StringBuilder selectBusinessLineSql = new StringBuilder();
            selectBusinessLineSql.append("SELECT T.ywlx FROM `" + ywxlTableName + "` T WHERE T.xlmc = '" + hdjb + "'");
            ywlx = (String) entityManager.createNativeQuery(selectBusinessLineSql.toString()).getSingleResult();
        }

        String[] splitID = ids.toString().split(";");
        boolean useParam = true;
        // 若业务路线未定义，则未传入活动级别，后续根据id查找业务路线
        if ("Undefined".equals(ywlx)) {
            useParam = false;
        }

        String kcsbNewTableName = getBizObjectFacade().getTableName("kcsbNew");
        Map<String, Map<String, Object>> fMap = new HashMap<>();
        // 处理传入的id拼接数据
        for (int j = 0; j < splitID.length; j++) {
            String subDqyw = "";
            String subYwlx = "";
            StringBuilder selectCourseInfoSql = new StringBuilder();
            selectCourseInfoSql.append("SELECT * FROM `" + kcsbNewTableName + "` T WHERE T.id = '" + splitID[j] + "'");
            // 根据ID取得课程申报信息
            List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectCourseInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            if (!useParam) {
                subYwlx = (String) resultList.get(0).get("ShortTextYWLX");
                subDqyw = (String) resultList.get(0).get("ShortTextDQYW");
            } else {
                subYwlx = ywlx;
                subDqyw = dqyw;
            }
            String[] split = subYwlx.split(";");
            String xyjd = "";
            String userName = user.getName();
            if (StringUtils.isEmpty(subDqyw)) {
                subDqyw = split[0];
                if (split.length < 2) {
                    xyjd = "done";
                } else {
                    xyjd = split[1];
                }
            } else {
                for (int i = 0; i < split.length; i++) {
                    if (subDqyw.equals(split[i])) {
                        if (StringUtils.isNotEmpty(fallBack)) {
                            subDqyw = i > 0 ? split[i - 1] : "";
                            xyjd = split[i];
                        } else {
                            subDqyw = i < split.length - 1 ? split[i + 1] : "done";
                            xyjd = i < split.length - 2 ? split[i + 2] : "done";
                        }
                        break;
                    }
                }
                // 若当前节点为审批相关，则发起对应审批流程
//                if (subDqyw.contains("审批")) {
//                    // 活动ID
//                    String sbhdId = (String) resultList.get(0).get("RelevanceFormSBHD");
//                    StringBuilder getHdmcByIdSql = new StringBuilder();
//                    String sbhdNewTableName = getBizObjectFacade().getTableName("sbhdNew");
//                    getHdmcByIdSql.append("SELECT * FROM `" + sbhdNewTableName + "` T WHERE T.id = '" + sbhdId + "'");
//                    List<Map<String, Object>> hdmcList = entityManager.createNativeQuery(getHdmcByIdSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
//                    String hdmcId = (String) hdmcList.get(0).get("id");
//                    String hdmc = (String) hdmcList.get(0).get("hdmc");
//                    // 获取发起活动的部门
//                    DepartmentModel dept = getOrganizationFacade().getDepartment((String) hdmcList.get(0).get("ownerDeptId"));
//                    if (!fMap.containsKey(hdmcId)) {
//                        // 新增活动单位
//                        Map<String, Object> smap = new HashMap<>();
//                        // 子表
//                        smap.put("SheetInfo", new ArrayList<>());
//                        // 活动名称_发起人一级部门
//                        smap.put("SText_actvNameAndDeptLevOne", hdmc + "_" + dept.getName());
//                        fMap.put(hdmcId, smap);
//                    }
//                    Map<String, Object> dqHdmc = fMap.get(hdmcId);
//                    List courseList = (List) dqHdmc.get("SheetInfo");
//                    Map<String, Object> courseInfo = new HashMap<>();
//                    // 工号
//                    courseInfo.put("ShortText_employeeNum", resultList.get(0).get("kczkfrgh"));
//                    // 姓名
//                    courseInfo.put("StaffSingle_name", resultList.get(0).get("kczkfr"));
//                    // 课程/案例名称
//                    courseInfo.put("SText_caseName", resultList.get(0).get("courseName"));
//                    // todo 其它课程内容信息
//                    courseInfo.put("rowStatus", "Added");
//                    courseList.add(courseInfo);
//                    dqHdmc.put("SheetInfo", courseList);
//                    fMap.put(hdmcId, dqHdmc);
//                }
            }

            Map<String, Object> paramMap = new HashMap<>();
            // 课程申报选择
            paramMap.put("RelevanceFormKCSB", splitID[j]);
            // 课程评审ID
            paramMap.put("ShortTextKCPSID", splitID[j]);
            // 当前审批人
            paramMap.put("ShortTextDQSPR", userName);
            // 当前节点
            paramMap.put("ShortTextDQJD", subDqyw);
            // 下一节点
            paramMap.put("ShortTextXYJD", xyjd);
            // 审核时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            paramMap.put("DateSHSJ", format.format(new Date()));
            BizObjectCreatedModel checkInfo = new BizObjectCreatedModel("shrz", paramMap, false);
            checkInfo.setSequenceStatus(SequenceStatus.COMPLETED.name());
            String checkInfoId = getBizObjectFacade().saveBizObject(adminId, checkInfo, false);
            log.info("\n=======▼▼▼▼▼▼审核日志表单保存成功,bizObjectId={}",checkInfoId);
            StringBuilder updateDQYWsql = new StringBuilder();
            updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ShortTextDQYW = '" + subDqyw + "' WHERE T.id = '" + splitID[j] + "'");
            int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
            log.info("\n=======▼▼▼▼▼▼更新业务状态成功,updateNum={}",updateNum);
        }
//        for (Map.Entry<String, Map<String, Object>> entry : fMap.entrySet()) {
//            Map<String, Object> map = entry.getValue();
//            // 发起基层领导审批流程
//            BizObjectCreatedModel departmentLeaderApproval = new BizObjectCreatedModel("DepartmentLeaderApproval", map, false);
//            String bizObjectId = getBizObjectFacade().saveBizObject(adminId, departmentLeaderApproval, false);
//            String instanceId = getWorkflowInstanceFacade().startWorkflowInstance(user.getDepartmentId(), adminId, "deptManagerApproveFlow", bizObjectId, true);
//            log.info("\n=======基层领导审批流程发起成功,instanceId={}",instanceId);
//        }
        return getOkResponseResult(ywlx, "success");
    }

    /**
     * 根据活动级别获取活动业务路线（取日志业务路线，推进日志，不更新业务节点）
     * @param hdjb
     * @return
     */
    @GetMapping("/businessLineTwo")
    @Transactional
    public ResponseResult<String> businessLineTwo(@RequestParam(required = false) String hdjb, @RequestParam(required = false) String dqyw, @RequestParam String kcsbId, @RequestParam(required = false) String fallBack) {

        // 业务路线
        String ywlx = "Undefined";

        String userId = getUserId();
        UserModel user = getOrganizationFacade().getUser(userId);

        // 如果参数传入活动级别，则依据活动级别获取业务路线
        if (StringUtils.isNotEmpty(hdjb)) {
            String ywxlTableName = getBizObjectFacade().getTableName("ywxlNew");
            StringBuilder selectBusinessLineSql = new StringBuilder();
            selectBusinessLineSql.append("SELECT T.ywlx FROM `" + ywxlTableName + "` T WHERE T.xlmc = '" + hdjb + "'");
            ywlx = (String) entityManager.createNativeQuery(selectBusinessLineSql.toString()).getSingleResult();
        }

        String[] splitID = kcsbId.split(";");
        boolean useParam = true;
        // 若业务路线未定义，则未传入活动级别，后续根据id查找业务路线
        if ("Undefined".equals(ywlx)) {
            useParam = false;
        }

        String kcsbNewTableName = getBizObjectFacade().getTableName("kcsbNew");
        String shrzTableName = getBizObjectFacade().getTableName("shrz");
        Map<String, Map<String, Object>> fMap = new HashMap<>();
        // 处理传入的id拼接数据
        for (int j = 0; j < splitID.length; j++) {
            String subDqyw = "";
            String subYwlx = "";
            StringBuilder selectCourseInfoSql = new StringBuilder();
            StringBuilder selectCourseLogSql = new StringBuilder();
            selectCourseInfoSql.append("SELECT * FROM `" + kcsbNewTableName + "` T WHERE T.id = '" + splitID[j] + "'");
            selectCourseLogSql.append("SELECT * FROM `" + shrzTableName + "` T WHERE T.ShortTextKCPSID = '" + splitID[j] + "' ORDER BY T.createdTime DESC LIMIT 1");
            // 根据ID取得课程申报信息
            List<Map<String, Object>> resultList = entityManager.createNativeQuery(selectCourseInfoSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            // 根据ID取得课程日志最新数据的下一节点为当前节点
            List<Map<String, Object>> logResultList = entityManager.createNativeQuery(selectCourseLogSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
            if (!useParam) {
                subYwlx = (String) resultList.get(0).get("ShortTextYWLX");
                subDqyw = (String) logResultList.get(0).get("ShortTextXYJD");
            } else {
                subYwlx = ywlx;
                subDqyw = dqyw;
            }
            String[] split = subYwlx.split(";");
            String xyjd = "";
            String dBdqyw = "";
            String dBxyjd = "";
            String userName = user.getName();
            if (StringUtils.isEmpty(subDqyw)) {
                subDqyw = split[0];
                if (split.length < 2) {
                    xyjd = "done";
                } else {
                    xyjd = split[1];
                }
            } else {
                for (int i = 0; i < split.length; i++) {
                    if (subDqyw.equals(split[i])) {
                        if (StringUtils.isNotEmpty(fallBack)) {
                            dBdqyw = subDqyw;
                            subDqyw = i > 0 ? split[i - 1] : "";
                            dBxyjd = subDqyw;
                            xyjd = split[i];
                        } else {
                            dBdqyw = subDqyw;
                            subDqyw = i < split.length - 1 ? split[i + 1] : "done";
                            dBxyjd = subDqyw;
                            xyjd = i < split.length - 2 ? split[i + 2] : "done";
                        }
                        break;
                    }
                }
                // 若当前节点为审批相关，则发起对应审批流程
                if (subDqyw.contains("审批")) {
                    // 活动ID
                    String sbhdId = (String) resultList.get(0).get("RelevanceFormSBHD");
                    StringBuilder getHdmcByIdSql = new StringBuilder();
                    String sbhdNewTableName = getBizObjectFacade().getTableName("sbhdNew");
                    getHdmcByIdSql.append("SELECT * FROM `" + sbhdNewTableName + "` T WHERE T.id = '" + sbhdId + "'");
                    List<Map<String, Object>> hdmcList = entityManager.createNativeQuery(getHdmcByIdSql.toString()).unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).getResultList();
                    String hdmcId = (String) hdmcList.get(0).get("id");
                    String hdmc = (String) hdmcList.get(0).get("hdmc");
                    // 获取发起活动的部门
                    DepartmentModel dept = getOrganizationFacade().getDepartment((String) hdmcList.get(0).get("ownerDeptId"));
                    if (!fMap.containsKey(hdmcId)) {
                        // 新增活动单位
                        Map<String, Object> smap = new HashMap<>();
                        // 子表
                        smap.put("SheetInfo", new ArrayList<>());
                        // 活动名称_发起人一级部门
                        smap.put("SText_actvNameAndDeptLevOne", hdmc + "_" + dept.getName());
                        fMap.put(hdmcId, smap);
                    }
                    Map<String, Object> dqHdmc = fMap.get(hdmcId);
                    List courseList = (List) dqHdmc.get("SheetInfo");
                    Map<String, Object> courseInfo = new HashMap<>();
                    // 课程ID
                    courseInfo.put("ShortTextCourseID", resultList.get(0).get("id"));
                    // 工号
                    courseInfo.put("ShortText_employeeNum", resultList.get(0).get("kczkfrgh"));
                    // 姓名
                    courseInfo.put("StaffSingle_name", resultList.get(0).get("kczkfr"));
                    // 课程/案例名称
                    courseInfo.put("SText_caseName", resultList.get(0).get("courseName"));
                    // 推荐结果
                    courseInfo.put("ShortText_marketing", resultList.get(0).get("tjjg"));
                    // 审批状态
                    courseInfo.put("ShortText_approvalStatus", resultList.get(0).get("currentAuditstate"));
                    // 部门
                    courseInfo.put("ShortText_departLevelTwo", resultList.get(0).get("xmb"));
                    // 单位
                    courseInfo.put("ShortText_unit", resultList.get(0).get("szdw"));
                    // 课程/案例类别
                    courseInfo.put("ShortText_SText_caseType", resultList.get(0).get("category"));
                    // 课时
                    courseInfo.put("ShortText_spendTime", resultList.get(0).get("classHour"));
                    // 培训对象
                    courseInfo.put("ShortText_caseTarget", resultList.get(0).get("cultivateObj"));
                    // 参与人
                    courseInfo.put("StaffMulti_CYR", resultList.get(0).get("tdcy"));
                    // 基层评审得分
                    courseInfo.put("ShortText_basicScore", resultList.get(0).get("jcpsdf"));
                    // 推荐结果
                    courseInfo.put("ShortText_basicMarketing", resultList.get(0).get("tjjg"));
                    // 审批结果
                    courseInfo.put("ShortText_approvalResult", resultList.get(0).get("shjg"));

                    courseInfo.put("rowStatus", "Added");
                    courseList.add(courseInfo);
                    dqHdmc.put("SheetInfo", courseList);
                    fMap.put(hdmcId, dqHdmc);
                }
            }

            Map<String, Object> paramMap = new HashMap<>();
            // 课程申报选择
            paramMap.put("RelevanceFormKCSB", splitID[j]);
            // 课程评审ID
            paramMap.put("ShortTextKCPSID", splitID[j]);
            // 当前审批人
            paramMap.put("ShortTextDQSPR", userName);

            // 当前节点
            paramMap.put("ShortTextDQJD", dBdqyw);
            // 下一节点
            paramMap.put("ShortTextXYJD", dBxyjd);

            // 审核时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            paramMap.put("DateSHSJ", format.format(new Date()));
            BizObjectCreatedModel checkInfo = new BizObjectCreatedModel("shrz", paramMap, false);
            checkInfo.setSequenceStatus(SequenceStatus.COMPLETED.name());
            String checkInfoId = getBizObjectFacade().saveBizObject(userId, checkInfo, false);
            log.info("\n=======审核日志表单保存成功,bizObjectId={}",checkInfoId);
            StringBuilder updateDQYWsql = new StringBuilder();
            updateDQYWsql.append("UPDATE `" + kcsbNewTableName + "` T set T.ShortTextDQYW = '" + subDqyw + "' WHERE T.id = '" + splitID[j] + "'");
//            int updateNum = entityManager.createNativeQuery(updateDQYWsql.toString()).executeUpdate();
//            log.info("\n=======更新业务状态成功,updateNum={}",updateNum);
        }
//        for (Map.Entry<String, Map<String, Object>> entry : fMap.entrySet()) {
////            Map<String, Object> map = entry.getValue();
////            // 发起基层领导审批流程
////            BizObjectCreatedModel departmentLeaderApproval = new BizObjectCreatedModel("DepartmentLeaderApproval", map, false);
////            String bizObjectId = getBizObjectFacade().saveBizObject(userId, departmentLeaderApproval, false);
////            String instanceId = getWorkflowInstanceFacade().startWorkflowInstance(user.getDepartmentId(), userId, "deptManagerApproveFlow", bizObjectId, true);
////            log.info("\n=======基层领导审批流程发起成功,instanceId={}",instanceId);
////        }
        return getOkResponseResult(ywlx, "success");
    }
}
